package com.chenx.config;

import org.springframework.util.CollectionUtils;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.Set;

/**
 * TODO
 *
 * @author chenx
 * @date 2021/6/16
 */
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    /*

    Servlet 3.0+容器启动时将自动扫描类路径以查找实现Spring的Webapplicationinitializer接口的所有实现，
    将其放进一个Set集合中，提供给ServletContainerInitializer中onStartup方法的第一个参数

     */
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        System.out.println("MySpringServletContainerInitializer onStartup");
        if (CollectionUtils.isEmpty(set)){
            return;
        }
        for (Class<?> clazz : set) {
            try {
                MyWebApplicationInitializer myWebApplicationInitializer = (MyWebApplicationInitializer) clazz.newInstance();
                //调用MyWebApplicationInitializer的onstartup方法
                myWebApplicationInitializer.onStartup(servletContext);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
    }
}
